/*
 * @Description: 原文检测 - 真实性检测
 * @Author: Rfan
 * @Date: 2022-10-10 14:19:09
 * @LastEditTime: 2022-10-21 18:11:46
 */

import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Button, Checkbox, Divider, Space } from 'antd';
import cs from 'classnames';
import classnames from 'classnames/bind';
import {
  CheckProps,
  EnumAuthenticityRuleType,
  EnumOriginalSourceRuleType
} from '../../../../../../dictionaries';
import { editItemById, insertItem, selectItemByKey } from '@/utils/list';
import type { IPropsRule } from '../../../../../../interface';
import styles from '../../../styles/entryPanes.module.scss';
import mainStyles from '../../../styles/main.module.scss';
import { useAddPlanDialogContext } from '@/view/system/ArchivesDetection/components/dialogs/AddPlan/contexts/AddPlanDialogContext';
import { isNullObj } from '@/utils';

const cx = classnames.bind(styles);
const mainCx = classnames.bind(mainStyles);

// 真实性字段规则类型
export interface IIntegrityFieldRules {
  ruleType: EnumAuthenticityRuleType.OriginalSourceAuthenticity;
  ruleValid: Boolean;
  rules: IPropsRule<EnumOriginalSourceRuleType>[];
}

// 条目真实性规则列表类型
type OriAuthRules = (IIntegrityFieldRules | IPropsRule<EnumAuthenticityRuleType>)[];

// 条目真实性完整类型
interface IAuthenticationFullRules {
  ruleType: CheckProps.Authenticity;
  rules: OriAuthRules;
}

const OriginalAuthentication = (props: any, ref: any) => {
  const { currentRuleInfo, getPropertyRules, getRuleState, setRuleState } =
    useAddPlanDialogContext();

  // 原文真实性规则数据
  const [ruleList, setRuleList] = useState<OriAuthRules>([]);

  useImperativeHandle(ref, () => ({
    save: () => {
      const fullRules: IAuthenticationFullRules = {
        ruleType: CheckProps.Authenticity,
        rules: ruleList
      };
      return fullRules;
    }
  }));

  /**
   * @description: 获取到规则后回写
   */
  useEffect(() => {
    if (currentRuleInfo && !isNullObj(currentRuleInfo)) {
      const ruleObj = getPropertyRules(CheckProps.Authenticity);
      setRuleList(ruleObj?.rules || []);
    }
  }, [currentRuleInfo]);

  /**
   * @description: 获取规则选中状态
   * @param {EnumOriginalSourceRuleType} type 真实性检测类型
   * @return {boolean} 选中状态
   */
  const getAuthenticityRuleState = (type: EnumOriginalSourceRuleType): boolean => {
    const authData = selectItemByKey(
      EnumAuthenticityRuleType.OriginalSourceAuthenticity,
      ruleList,
      'ruleType'
    );
    if (authData) {
      const authRule = selectItemByKey(type, authData.rules || [], 'ruleType');
      return authRule?.ruleValid;
    } else {
      return false;
    }
  };

  /**
   * @description: 设置规则选中状态
   * @param {boolean} valid 选中状态
   * @param {EnumAuthenticityRuleType} type 真实性检测类型
   */
  const setAuthenticityRuleState = (valid: boolean, type: EnumOriginalSourceRuleType) => {
    const currAuthData: IIntegrityFieldRules = selectItemByKey(
      EnumAuthenticityRuleType.OriginalSourceAuthenticity,
      ruleList,
      'ruleType'
    );
    // 找到真实性规则，没有则新增
    const authData: IIntegrityFieldRules = currAuthData || {
      ruleType: EnumAuthenticityRuleType.OriginalSourceAuthenticity,
      ruleValid: false,
      rules: []
    };
    // 真实性规则下的规则列表
    const authList = authData?.rules || [];
    // 找到改变的规则
    const currentRule = selectItemByKey(type, authList, 'ruleType');
    const editRule = currentRule
      ? editItemById(type, { ...currentRule, ruleValid: valid }, authList, 'ruleType')
      : insertItem({ ruleType: type, ruleValid: valid }, authList);
    authData.rules = editRule;
    console.log('setAuthenticityRuleState', { authData, authList, currentRule, editRule });
    setRuleList((state) =>
      currAuthData
        ? editItemById(
            EnumAuthenticityRuleType.OriginalSourceAuthenticity,
            authData,
            state,
            'ruleType'
          )
        : insertItem(authData, state)
    );
  };

  return (
    <div className={cs(mainCx('property-wrap'), cx('property-authenticity'))}>
      <Space className={mainCx('property--title-wrap')} align="center">
        <h6 className={mainCx('property--title')}>电子原文检测</h6>
        <div className={mainCx('select-btn')}>
          <Button type="text" size="small">
            全选
          </Button>{' '}
          /{' '}
          <Button type="text" size="small">
            反选
          </Button>
        </div>
      </Space>
      <Space direction="vertical">
        <Space>
          <Checkbox
            checked={getRuleState(EnumAuthenticityRuleType.OriginalSourceAuthenticity, ruleList)}
            onChange={(evt) => {
              setRuleState(
                evt.target.checked,
                EnumAuthenticityRuleType.OriginalSourceAuthenticity,
                ruleList,
                setRuleList
              );
            }}
          >
            电子文件来源真实性检测，电子文件的固化信息
          </Checkbox>
          <Divider type="vertical" />
          <Space>
            <Checkbox
              checked={getAuthenticityRuleState(EnumOriginalSourceRuleType.DataDigest)}
              onChange={(evt) => {
                setAuthenticityRuleState(evt.target.checked, EnumOriginalSourceRuleType.DataDigest);
              }}
            >
              数据摘要
            </Checkbox>
            <Checkbox
              checked={getAuthenticityRuleState(EnumOriginalSourceRuleType.ElectronicSign)}
              onChange={(evt) => {
                setAuthenticityRuleState(
                  evt.target.checked,
                  EnumOriginalSourceRuleType.ElectronicSign
                );
              }}
            >
              电子签名
            </Checkbox>
            <Checkbox
              checked={getAuthenticityRuleState(EnumOriginalSourceRuleType.ElectronicSeal)}
              onChange={(evt) => {
                setAuthenticityRuleState(
                  evt.target.checked,
                  EnumOriginalSourceRuleType.ElectronicSeal
                );
              }}
            >
              电子印章
            </Checkbox>
            <Checkbox
              checked={getAuthenticityRuleState(EnumOriginalSourceRuleType.Timestamp)}
              onChange={(evt) => {
                setAuthenticityRuleState(evt.target.checked, EnumOriginalSourceRuleType.Timestamp);
              }}
            >
              时间戳
            </Checkbox>
          </Space>
        </Space>
        <Checkbox
          checked={getRuleState(EnumAuthenticityRuleType.OriginalProperty, ruleList)}
          onChange={(evt) => {
            setRuleState(
              evt.target.checked,
              EnumAuthenticityRuleType.OriginalProperty,
              ruleList,
              setRuleList
            );
          }}
        >
          属性一致性检测，电子文件的电子属性与元数据记录一致
        </Checkbox>
        <Checkbox
          checked={getRuleState(EnumAuthenticityRuleType.OriginalRelation, ruleList)}
          onChange={(evt) => {
            setRuleState(
              evt.target.checked,
              EnumAuthenticityRuleType.OriginalRelation,
              ruleList,
              setRuleList
            );
          }}
        >
          关联一致性检测，元数据中记录的文件存储位置与实际位置
        </Checkbox>
      </Space>
    </div>
  );
};

export default forwardRef(OriginalAuthentication);
